package edu.luas.digitalmedia.controller;

import edu.luas.digitalmedia.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class UserLoginController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1:设置请求编码
        req.setCharacterEncoding("utf-8");
        //2:设置响应编码
        resp.setContentType("text/html;charset=utf-8");
        //3:获取请求参数
        String strYhm = req.getParameter("username");
        String strMm = req.getParameter("password");
        if (strYhm == null) strYhm = "";
        if (strMm == null) strMm = "";
        if (strYhm.trim().equals("") || strMm.trim().equals("")) {
            resp.getWriter().print("用户名或密码为空！请重试。");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        } else {
            // 验证用户登录
            boolean authenticated = false;
            try {
                authenticated = new UserService().authenticateUser(strYhm, strMm);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (authenticated) {
                resp.getWriter().print("登录成功！");
                // 进行登录成功后的处理逻辑，例如跳转到首页
                req.getRequestDispatcher("index.jsp").forward(req,resp);
            } else {
                resp.getWriter().print("登录失败，请检查用户名和密码。");
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }
        }
    }
}